IRCBot::Plugin.define "dieroll" do
	help_string "Throws dice/coins. Syntax: \"/me flips a coin\", \"/me flips n coins\" or \"/me rolls (dice)d(sides)\""
	def privmsg_function(user,target,message,usermask)
		if message.start_with?("#{1.chr}ACTION") then
			message = message.gsub(1.chr,"").sub("ACTION","").strip.downcase
			if message.downcase == 'flips a coin' then
				privmsg(target,dieroll(1,2))
			elsif message =~ /^flips\s[0-9]+\scoins/ then
				coins = message.sub('flips','').sub('coins','').strip.to_i
				privmsg(target,dieroll(coins,2))
			elsif message.start_with?('rolls') then
				if message.sub('rolls','').strip =~ /^[0-9]+d[0-9]+/ then
					message = message.sub('rolls','').strip
					match = message.split('d')
					privmsg(target,dieroll(match[0].to_i,match[1].to_i))
				end
			end
		end
	end
	
	def dieroll(dice,sides)
		puts "Dice: #{dice}"
		puts "Sides: #{sides}"
		i = 0
		sum = 0
		resultarray = []
		if dice <= 10 and sides <= 20000 then
			while i < dice
				i += 1
				result = rand(sides) +1
				sum += result
				resultarray.push result
			end
		end
		if sum == 0 or sides <2 then
			return "You fail at making plausible dice."
		else
			if sides == 2 then
				coinresult = []
				heads = 0
				tails = 0
				for result in resultarray
					if result == 1 then
						coinresult.push 'Heads'
						heads += 1
					else
						coinresult.push 'Tails'
						tails += 1
					end
				end
				
				return coinresult.join(', ')+". Heads: #{heads}. Tails: #{tails}."
			else
				return resultarray.join(", ")+". Total: "+sum.to_s
			end
		end
	end
end
